package com.newlink.building.utils

import android.content.Context
import com.alibaba.sdk.android.push.CommonCallback
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory
import com.newlink.building.common_base.utils.NLog

/**
 * 推送服务帮助类
 * 提供推送服务的兜底处理方案
 */
object NL_PushServiceHelper {

    /**
     * 检查推送通道状态，包含兜底处理
     */
    fun checkPushChannelStatus(context: Context, callback: CommonCallback? = null) {
        try {
            val pushService = PushServiceFactory.getCloudPushService()
            pushService.checkPushChannelStatus(object : CommonCallback {
                override fun onSuccess(response: String?) {
                    NLog.e("[PushServiceHelper] checkPushChannelStatus success: $response")
                    callback?.onSuccess(response)
                }

                override fun onFailed(errorCode: String?, errorMsg: String?) {
                    NLog.e("[PushServiceHelper] checkPushChannelStatus failed - errorCode:$errorCode, errorMsg:$errorMsg")

                    // 处理 deviceId 为空的错误
                    when (errorCode) {
                        "PUSH_20101" -> {
                            handleDeviceIdEmptyError(context)
                        }
                        "PUSH_10003" -> {
                            NLog.e("[PushServiceHelper] Network error, will retry later")
                        }
                        "PUSH_10001" -> {
                            NLog.e("[PushServiceHelper] Invalid parameters")
                        }
                        "-29" -> {
                            NLog.e("[PushServiceHelper] Connection strategy not available - likely network/DNS issue")
                            handleNetworkConnectivityError(context)
                        }
                        else -> {
                            NLog.e("[PushServiceHelper] Unknown push error: $errorCode")
                        }
                    }

                    callback?.onFailed(errorCode, errorMsg)
                }
            })
        } catch (e: Exception) {
            NLog.e("[PushServiceHelper] Exception in checkPushChannelStatus: ${e.message}")
            callback?.onFailed("EXCEPTION", e.message)
        }
    }

    /**
     * 处理网络连接错误
     */
    private fun handleNetworkConnectivityError(context: Context) {
        NLog.e("[PushServiceHelper] Handling network connectivity error (-29)")

        if (NL_DeviceIdHelper.isEmulator()) {
            NLog.e("[PushServiceHelper] Running on emulator - Aliyun push service may not be accessible")
            NLog.e("[PushServiceHelper] This is expected behavior in emulator environment")
            NLog.e("[PushServiceHelper] Suggestion: Test push notifications on real device")
        } else {
            NLog.e("[PushServiceHelper] Network connectivity issue on real device")
            NLog.e("[PushServiceHelper] Please check network settings and firewall")
        }

        setPushServiceStatus(context, false)
    }

    /**
     * 处理设备ID为空的错误
     */
    private fun handleDeviceIdEmptyError(context: Context) {
        NLog.e("[PushServiceHelper] Handling deviceId empty error")

        val fallbackDeviceId = NL_DeviceIdHelper.getDeviceId(context)
        NLog.e("[PushServiceHelper] Fallback deviceId: $fallbackDeviceId")

        // 记录模拟器信息
        if (NL_DeviceIdHelper.isEmulator()) {
            NLog.e("[PushServiceHelper] Running on emulator, push service may have limitations")
            NLog.e("[PushServiceHelper] Device info: ${NL_DeviceIdHelper.getDeviceInfo(context)}")
        }

        // 可以考虑设置一个标志，表示推送服务暂时不可用
        // 或者尝试其他推送方案（如Firebase）
        setPushServiceStatus(context, false)
    }

    /**
     * 注册推送服务，包含错误处理
     */
    fun registerPushService(context: Context, callback: CommonCallback? = null) {
        try {
            val pushService = PushServiceFactory.getCloudPushService()
            pushService.register(
                context,
                object : CommonCallback {
                    override fun onSuccess(response: String?) {
                        NLog.e("[PushServiceHelper] register success: $response")
                        setPushServiceStatus(context, true)
                        callback?.onSuccess(response)
                    }

                    override fun onFailed(errorCode: String?, errorMsg: String?) {
                        NLog.e("[PushServiceHelper] register failed - errorCode:$errorCode, errorMsg:$errorMsg")
                        setPushServiceStatus(context, false)

                        when (errorCode) {
                            "PUSH_20101" -> handleDeviceIdEmptyError(context)
                            "-29" -> handleNetworkConnectivityError(context)
                        }

                        callback?.onFailed(errorCode, errorMsg)
                    }
                }
            )
        } catch (e: Exception) {
            NLog.e("[PushServiceHelper] Exception in registerPushService: ${e.message}")
            setPushServiceStatus(context, false)
            callback?.onFailed("EXCEPTION", e.message)
        }
    }

    /**
     * 获取设备ID，优先使用阿里云的，失败则使用兜底方案
     */
    fun getDeviceId(context: Context): String {
        return try {
            val aliyunDeviceId = PushServiceFactory.getCloudPushService().deviceId
            if (!aliyunDeviceId.isNullOrEmpty()) {
                aliyunDeviceId
            } else {
                NL_DeviceIdHelper.getDeviceId(context)
            }
        } catch (e: Exception) {
            NLog.e("[PushServiceHelper] Failed to get Aliyun deviceId: ${e.message}")
            NL_DeviceIdHelper.getDeviceId(context)
        }
    }

    /**
     * 设置推送服务状态
     */
    private fun setPushServiceStatus(context: Context, isAvailable: Boolean) {
        val prefs = context.getSharedPreferences("push_service_prefs", Context.MODE_PRIVATE)
        prefs.edit()
            .putBoolean("push_service_available", isAvailable)
            .putLong("last_check_time", System.currentTimeMillis())
            .apply()

        NLog.e("[PushServiceHelper] Push service status set to: $isAvailable")
    }

    /**
     * 获取推送服务状态
     */
    fun isPushServiceAvailable(context: Context): Boolean {
        val prefs = context.getSharedPreferences("push_service_prefs", Context.MODE_PRIVATE)
        return prefs.getBoolean("push_service_available", true)
    }

    /**
     * 获取推送服务诊断信息
     */
    fun getDiagnosticInfo(context: Context): String {
        val isAvailable = isPushServiceAvailable(context)
        val deviceId = getDeviceId(context)
        val isEmulator = NL_DeviceIdHelper.isEmulator()

        return """
            Push Service Diagnostic Info:
            - Service Available: $isAvailable
            - Device ID: $deviceId
            - Is Emulator: $isEmulator
            - Device Info: ${if (isEmulator) NL_DeviceIdHelper.getDeviceInfo(context) else "Real Device"}
        """.trimIndent()
    }
}
